package org.springblade.tms.module.demandextrainfo.base;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import lombok.AllArgsConstructor;
import org.springblade.system.entity.DictBiz;
import org.springblade.system.feign.IDictBizClient;
import org.springblade.tms.global.constant.DictCodeConstant;
import org.springblade.tms.global.enums.*;
import org.springblade.tms.global.exception.CommonException;
import org.springblade.tms.module.demandextrainfo.entity.TmDemandExtraInfo;
import org.springblade.tms.module.demandextrainfo.service.ITmDemandExtraInfoService;
import org.springblade.tms.module.demandextrainfo.vo.TmDemandExtraInfoVO;
import org.springblade.tms.module.demandorder.entity.TMDemandOrder;
import org.springblade.tms.module.demandorder.service.IDemandOrderService;
import org.springblade.tms.module.demandorder.vo.TMDemandEventVO;
import org.springblade.tms.module.demandorderitem.entity.TMDemandOrderItem;
import org.springblade.tms.module.demandorderitem.service.IDemandOrderItemService;
import org.springblade.tms.module.sap.base.SapRequestService;
import org.springblade.tms.module.sap.dto.SapTransportOrderDTO;
import org.springblade.tms.module.sap.dto.SapTransportOrderItemDTO;
import org.springblade.tms.module.sap.dto.WaybillEventDTO;
import org.springblade.tms.module.supercargoinfo.entity.TMSupercargoInfo;
import org.springblade.tms.module.supercargoinfo.service.ISupercargoInfoService;
import org.springblade.tms.module.transportorder.entity.TMTransportOrder;
import org.springblade.tms.module.transportorder.service.ITransportOrderService;
import org.springblade.tms.module.transportorderitem.entity.TMTransportOrderItem;
import org.springblade.tms.module.transportorderitem.service.ITransportOrderItemService;
import org.springblade.tms.module.userinfo.entity.TMUserInfo;
import org.springblade.tms.module.userinfo.service.IUserInfoService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@Service
@AllArgsConstructor
@Transactional
public class DemandExtraService {

	private final IDemandOrderService demandOrderService;

	private final IDictBizClient dictClient;

	private final SapRequestService sapRequestService;

	private final ITmDemandExtraInfoService tmDemandExtraInfoService;

	private final IDemandOrderItemService demandOrderItemService;

	private final ITransportOrderService transportOrderService;

	private final ITransportOrderItemService transportOrderItemService;

	private final IUserInfoService userInfoService;

	private final ISupercargoInfoService supercargoInfoService;

	/***
	 * wzq
	 * @desc 推送外部系统补全信息
	 * @param demandId
	 */
	public void fillDemandExtra(Long demandId) {
		//查询货运订单
		TMDemandOrder order = demandOrderService.getById(demandId);
		checkDemandNull(order);
		checkDemandWait(order);

		//铁运
		List<DictBiz> dictListRail = dictClient.getList(DictCodeConstant.RAIL_DEMAND).getData();
		//海运
		List<DictBiz> dictListSea = dictClient.getList(DictCodeConstant.SEABORNE_DEMAND).getData();
		//构建请求sap参数
		SapTransportOrderDTO param = SapTransportOrderDTO.builder().build();

		//查询补充信息
		TmDemandExtraInfo info = tmDemandExtraInfoService.getOne(
			TmDemandExtraInfo.buildWrapper(1, TmDemandExtraInfo.builder().parentId(order.getId()).build())
		);
		param.setTdh(info.getDeliverNo());
		if (dictListRail.stream().anyMatch(item -> item.getDictKey().equals(order.getOrderType()))) {
			//推送铁运信息
			if (info == null) {
				CommonException.throwCommonException("铁运信息不存在");
			}
			BeanUtil.copyProperties(info, param, new CopyOptions().setIgnoreNullValue(true));

		} else if (dictListSea.stream().anyMatch(item -> item.getDictKey().equals(order.getOrderType()))) {
			//推送海运信息
			if (info == null) {
				CommonException.throwCommonException("海运信息不存在");
			}
			BeanUtil.copyProperties(info, param, new CopyOptions().setIgnoreNullValue(true));
		}
		param.setType(SapTransportActionEnum.DEMAND.value());
		param.setDeliverNo(order.getDeliverNo());
		param.setOrderNo(order.getOrderNo());
		param.setOrderType(order.getOrderType());
		param.setDemandId(demandId);
		param.setBoat(info.getBoat());
		List<TMDemandOrderItem> tmDemandOrderItems = demandOrderItemService.lambdaQuery().eq(TMDemandOrderItem::getParentId, demandId).list();
		List<SapTransportOrderItemDTO> sapTransportOrderItemDTOS = new ArrayList<>();
		for (TMDemandOrderItem tmDemandOrderItem : tmDemandOrderItems) {
			sapTransportOrderItemDTOS.add(org.springblade.core.tool.utils.BeanUtil.copy(tmDemandOrderItem, SapTransportOrderItemDTO.class));
		}
		param.setItem(sapTransportOrderItemDTOS);
		sapRequestService.pushTmForDemandExtraInfo(param);
	}


	/***
	 * wzq
	 * @desc 需求单补全信息操作
	 * @param extraInfo
	 */
	public Long fillDemandExtra(TmDemandExtraInfoVO extraInfo) {
		//查询货运订单
		TMDemandOrder order = demandOrderService.getById(extraInfo.getParentId());
		checkDemandNull(order);
		//查询是否已存在
		TmDemandExtraInfo info = tmDemandExtraInfoService.getOne(
			TmDemandExtraInfo.buildWrapper(1, TmDemandExtraInfo.builder().parentId(order.getId()).build())
		);
		if (info != null) {
			BeanUtil.copyProperties(extraInfo, info, new CopyOptions().setIgnoreNullValue(true));
		} else {
			info = extraInfo;
		}
		info.setOrderType(OrderTypeEnum.DEMAND_LIST.getValue());
		if (order.getOrderType().equals(TorTypeEnum.ZFB1.getValue()) || order.getOrderType().equals(TorTypeEnum.ZFB2.getValue())) {
			info.setTransportType(TransportTypeEnum.OCEAN_SHIPPING.getValue());
		} else if (order.getOrderType().equals(TorTypeEnum.ZFO3.getValue()) || order.getOrderType().equals(TorTypeEnum.ZFO9.getValue())) {
			info.setTransportType(TransportTypeEnum.RAIL_TRANSPORT.getValue());
		}
		tmDemandExtraInfoService.saveOrUpdate(info);
		//补全后就进行推送
		fillDemandExtra(order.getId());
		return info.getId();
	}

	/**
	 * @param extraInfo:
	 * @return Long
	 * @author yr
	 * @description 运输单补充信息
	 * @date 2022/6/15 11:20
	 */
	public Long fillTransportExtra(TmDemandExtraInfoVO extraInfo) {
		//查询货运订单
		TMTransportOrder order = transportOrderService.getById(extraInfo.getParentId());
		checkDemandNull(order);
		//查询是否已存在
		TmDemandExtraInfo info = tmDemandExtraInfoService.getOne(
			TmDemandExtraInfo.buildWrapper(1, TmDemandExtraInfo.builder().parentId(order.getId()).build())
		);
		if (info != null) {
			BeanUtil.copyProperties(extraInfo, info, new CopyOptions().setIgnoreNullValue(true));
		} else {
			info = extraInfo;
		}
		info.setOrderType(OrderTypeEnum.SINGLE_TRANSPORT.getValue());
		tmDemandExtraInfoService.saveOrUpdate(info);
		//补全后就进行推送
		fillTransportExtra(order.getId());
		return info.getId();
	}

	/***
	 * yr
	 * @desc 推送外部系统补全信息
	 * @param transportId
	 */
	public void fillTransportExtra(Long transportId) {
		//查询货运订单
		TMTransportOrder order = transportOrderService.getById(transportId);
		checkDemandNull(order);
		//构建请求sap参数
		SapTransportOrderDTO param = SapTransportOrderDTO.builder().build();
		param.setType(SapTransportActionEnum.TRANSPORT.value());
		param.setOrderNo(order.getOrderNo());
		//查询补充信息
		TmDemandExtraInfo info = tmDemandExtraInfoService.getOne(
			TmDemandExtraInfo.buildWrapper(1, TmDemandExtraInfo.builder().parentId(order.getId()).build())
		);
		param.setTdh(info.getDeliverNo());
		//推送铁运信息
		if (info == null) {
			CommonException.throwCommonException("运单补充信息信息不存在");
		}
		BeanUtil.copyProperties(info, param, new CopyOptions().setIgnoreNullValue(true));
		param.setDeliverNo(order.getDeliverNo());
		param.setTransportNo(order.getTransportNo());
		param.setBoat(info.getBoat());
		param.setOrderType(order.getOrderType());
		List<TMTransportOrderItem> transportOrderItems = transportOrderItemService.lambdaQuery().eq(TMTransportOrderItem::getParentId, transportId).list();
		List<SapTransportOrderItemDTO> sapTransportOrderItemDTOS = new ArrayList<>();
		for (TMTransportOrderItem tmTransportOrderItem : transportOrderItems) {
			sapTransportOrderItemDTOS.add(org.springblade.core.tool.utils.BeanUtil.copy(tmTransportOrderItem, SapTransportOrderItemDTO.class));
		}
		List<TMTransportOrderItem> list = transportOrderItemService.lambdaQuery().eq(TMTransportOrderItem::getParentId, order.getId()).list();
		org.springblade.core.tool.utils.BeanUtil.copyNonNull(order, param);
		TMUserInfo driver = userInfoService.getById(order.getDriverId());
		TMSupercargoInfo supercargoInfo = supercargoInfoService.getById(order.getSupercargoId());
		param.setDriverPhone(driver.getPhone());
		if (supercargoInfo != null) {
			param.setSupercargoPhone(supercargoInfo.getPhone());
			param.setIdCardNo(supercargoInfo.getIdCardNo());
		}
		param.setCertificateDriverNo(driver.getCertificateDriverNo());
		for (TMTransportOrderItem tmTransportOrderItem : list) {
			sapTransportOrderItemDTOS.add(org.springblade.core.tool.utils.BeanUtil.copy(tmTransportOrderItem, SapTransportOrderItemDTO.class));
		}
		param.setType(SapTransportActionEnum.TRANSPORT.value());
		param.setTransportNo(order.getTransportNo());
		param.setItem(sapTransportOrderItemDTOS);
		sapRequestService.pushTmForDemandExtraInfo(param);
	}

	/***
	 * wzq
	 * @desc 关闭需求单
	 * @param demandId
	 */
	public void closeDemand(Long demandId) {
		//查询货运订单
		TMDemandOrder order = demandOrderService.getById(demandId);
		checkDemandNull(order);
		order.setDemandStatus(DemandStatusEnum.FINISH.value());
		demandOrderService.updateById(order);
	}


	/********************************私有方法*****************************************/

	private void checkDemandNull(TMDemandOrder order) {
		if (Objects.isNull(order)) {
			CommonException.throwCommonException("需求单不存在");
		}
	}

	private void checkDemandNull(TMTransportOrder order) {
		if (Objects.isNull(order)) {
			CommonException.throwCommonException("运输单不存在");
		}
	}

	private void checkDemandWait(TMDemandOrder order) {
		if (
			!DemandStatusEnum.TO_BE_LOADED.value().equals(order.getDemandStatus())
				&&
				!DemandStatusEnum.TO_BE_SHIPPED.value().equals(order.getDemandStatus())
				&&
				!DemandStatusEnum.AWAITING_DELIVERY.value().equals(order.getDemandStatus())
				&&
				!DemandStatusEnum.ALREADY.value().equals(order.getDemandStatus())
		) {
			CommonException.throwCommonException("仅能操作[" +
				DemandStatusEnum.TO_BE_LOADED.description() +
				DemandStatusEnum.TO_BE_SHIPPED.description() +
				DemandStatusEnum.AWAITING_DELIVERY.description() +
				DemandStatusEnum.ALREADY.description()
				+ "]状态的需求单");
		}
	}


	/**
	 * 需求单时间变更
	 *
	 * @param input
	 */
	public void eventChange(TMDemandEventVO input) {
		//查询货运订单
		TMDemandOrder order = demandOrderService.getById(input.getDemandId());
		checkDemandNull(order);

		if (!DemandStatusEnum.beforeCheck(order.getDemandStatus(), input.getStatus())) {
			CommonException.throwCommonException(order.getDemandStatus() + "不能变更为" + input.getStatus());
		}
		String value = "";
		if (input.getStatus().equals(DemandStatusEnum.TO_BE_LOADED.value())) {
			value = EventCodeEnum.ARRIVE_AT_THE_PICK_UP_POINT.value();
		} else if (input.getStatus().equals(DemandStatusEnum.TO_BE_SHIPPED.value())) {
			value = EventCodeEnum.LOADED.value();
		} else if (input.getStatus().equals(DemandStatusEnum.AWAITING_DELIVERY.value())) {
			value = EventCodeEnum.SHIPPED.value();
		} else if (input.getStatus().equals(DemandStatusEnum.FINISH.value())) {
			value = EventCodeEnum.DELIVERED.value();
		}
		order.setDemandStatus(input.getStatus());
		demandOrderService.updateById(order);
		WaybillEventDTO waybillEventDTO = new WaybillEventDTO();
		org.springblade.core.tool.utils.BeanUtil.copyNonNull(order, waybillEventDTO);
		waybillEventDTO.setType(SapTransportActionEnum.DEMAND.value());
		waybillEventDTO.setEventCode(value);
		waybillEventDTO.setEventTime(LocalDateTime.now());
		waybillEventDTO.setTorId(order.getOrderNo());
		sapRequestService.pushTmForUpdateWaybill(waybillEventDTO);
	}
}
